import * as vscode from 'vscode';
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import * as fs from 'fs';
import * as path from 'path';

// 定义API响应类型
interface ApiResponse<T> {
    status: boolean;
    message: string;
    data: T;
}

// Token响应数据类型
interface TokenResponseData {
    token: string;
}

// 图片上传响应数据类型
interface UploadResponseData {
    key: string;
    name: string;
    pathname: string;
    origin_name: string;
    size: number;
    mimetype: string;
    extension: string;
    md5: string;
    sha1: string;
    links: {
        url: string;
        html: string;
        bbcode: string;
        markdown: string;
        markdown_with_link: string;
        thumbnail_url: string;
    };
}

// 策略列表响应数据类型
interface StrategyResponseData {
    strategies: Array<{
        id: number;
        name: string;
    }>;
}

// 相册列表响应数据类型
interface AlbumListResponseData {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    data: Array<{
        id: number;
        name: string;
        intro: string;
        image_num: number;
    }>;
}

// 图片列表响应数据类型
interface ImageListResponseData {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    data: Array<{
        key: string;
        name: string;
        origin_name: string;
        pathname: string;
        size: number;
        width: number;
        height: number;
        md5: string;
        sha1: string;
        human_date: string;
        date: string;
        links: {
            url: string;
            html: string;
            bbcode: string;
            markdown: string;
            markdown_with_link: string;
            thumbnail_url: string;
        };
    }>;
}

export class LsykApi {
    private context: vscode.ExtensionContext;
    private axiosInstance: AxiosInstance;
    private apiUrl: string = '';
    private email: string = '';
    private password: string = '';
    private token: string = '';
    private strategyId: number = 0;

    constructor(context: vscode.ExtensionContext) {
        this.context = context;
        this.loadConfig();

        // 尝试从本地文件加载缓存的token
        const cachedToken = this.loadCachedToken();
        if (cachedToken) {
            this.token = cachedToken;
        }

        // 创建axios实例
        this.axiosInstance = axios.create({
            baseURL: this.apiUrl,
            headers: {
                'Accept': 'application/json'
            }
        });

        // 添加请求拦截器，自动添加token
        this.axiosInstance.interceptors.request.use(config => {
            if (this.token) {
                config.headers.Authorization = `Bearer ${this.token}`;
            }
            return config;
        });
    }

    // 加载配置
    private loadConfig(): void {
        const config = vscode.workspace.getConfiguration('lsyk-upload-vs-plugin');
        this.apiUrl = config.get('apiUrl', 'https://lsky.top237.top/api/v1');
        this.email = config.get('email', '');
        this.password = config.get('password', '');
        this.strategyId = config.get('strategyId', 0);
    }

    // 保存token到实例和缓存文件
    private async saveToken(token: string): Promise<void> {
        this.token = token;
        // 缓存到本地文件
        await this.cacheTokenToFile(token);
    }

    // 检查token是否过期
    private async isTokenExpired(): Promise<boolean> {
        try {
            // 简单检查：发送一个需要token的请求，看是否成功
            const response = await this.axiosInstance.get('/profile');
            return false; // 请求成功，token有效
        } catch (error) {
            // 如果是401错误，说明token过期
            if (axios.isAxiosError(error)) {
                if (error.response?.status === 401) {
                    return true;
                }
                console.error('检查token过期时出错:', error.response?.status, error.response?.data);
            } else {
                console.error('检查token过期时出错:', error);
            }
            // 其他错误，保守认为token过期
            return true;
        }
    }

    // 获取token
    public async getToken(): Promise<string | null> {
        try {
            // 检查是否有缓存的token
            if (this.token) {
                // 检查token是否过期
                const isExpired = await this.isTokenExpired();
                if (!isExpired) {
                    return this.token;
                }
                vscode.window.showInformationMessage('token已过期，正在重新获取');
            }

            // 如果没有配置邮箱和密码，提示用户
            if (!this.email || !this.password) {
                vscode.window.showErrorMessage('请先配置蓝空图床的邮箱和密码');
                return null;
            }

            // 发送请求获取token
            vscode.window.showInformationMessage('正在获取token...');
            const response: AxiosResponse<ApiResponse<TokenResponseData>> = await this.axiosInstance.post(
                '/tokens',
                { email: this.email, password: this.password }
            );
            console.log('获取token响应:', response.data);
            if (response.data.status) {
                const token = response.data.data.token;
                await this.saveToken(token);
                vscode.window.showInformationMessage('获取token成功');
                return token;
            } else {
                vscode.window.showErrorMessage(`获取token失败: ${response.data.message}`);
                console.error('获取token失败响应:', response.data);
                return null;
            }
        } catch (error) {
            const errorMsg = error instanceof Error ? error.message : String(error);
            vscode.window.showErrorMessage(`获取token出错: ${errorMsg}`);
            console.error('获取token异常:', error);
            return null;
        }
    }

    // 缓存token到本地文件
    private async cacheTokenToFile(token: string): Promise<void> {
        try {
            const cacheDir = path.join(this.context.globalStorageUri.fsPath, 'cache');
            if (!fs.existsSync(cacheDir)) {
                fs.mkdirSync(cacheDir, { recursive: true });
            }
            const cacheFile = path.join(cacheDir, 'token.json');
            fs.writeFileSync(cacheFile, JSON.stringify({
                token: token,
                timestamp: Date.now()
            }));
        } catch (error) {
            console.error('缓存token到文件失败:', error);
        }
    }

    // 从本地文件加载缓存的token
    private loadCachedToken(): string | null {
        try {
            const cacheDir = path.join(this.context.globalStorageUri.fsPath, 'cache');
            const cacheFile = path.join(cacheDir, 'token.json');
            if (fs.existsSync(cacheFile)) {
                const data = fs.readFileSync(cacheFile, 'utf8');
                const cache = JSON.parse(data);
                // 检查token是否过期（7天有效期）
                if (Date.now() - cache.timestamp < 7 * 24 * 60 * 60 * 1000) {
                    return cache.token;
                }
            }
            return null;
        } catch (error) {
            console.error('从文件加载token失败:', error);
            return null;
        }
    }

    // 上传图片
    public async uploadImage(filePath: string, albumId?: number): Promise<ApiResponse<UploadResponseData> | null> {
        try {
            // 确保有token
            const token = await this.getToken();
            if (!token) {
                return null;
            }

            // 检查文件是否存在
            if (!fs.existsSync(filePath)) {
                vscode.window.showErrorMessage(`文件不存在: ${filePath}`);
                return null;
            }

            // 准备表单数据
            const formData = new FormData();
            const fileContent = fs.readFileSync(filePath);
            const fileName = path.basename(filePath);

            // @ts-ignore - FormData types can be tricky
            formData.append('file', new Blob([fileContent]), fileName);

            // 如果有策略ID，添加到表单
            if (this.strategyId > 0) {
                formData.append('strategy_id', this.strategyId.toString());
            }

            // 如果有相册ID，添加到表单
            if (albumId) {
                formData.append('album_id', albumId.toString());
            }

            // 发送上传请求
            const response: AxiosResponse<ApiResponse<UploadResponseData>> = await this.axiosInstance.post(
                '/upload',
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
            );

            return response.data;
        } catch (error) {
            vscode.window.showErrorMessage(`上传图片出错: ${error instanceof Error ? error.message : String(error)}`);
            return null;
        }
    }

    // 获取策略列表
    public async getStrategies(): Promise<ApiResponse<StrategyResponseData> | null> {
        try {
            // 确保有token
            const token = await this.getToken();
            if (!token) {
                return null;
            }

            // 发送请求
            const response: AxiosResponse<ApiResponse<StrategyResponseData>> = await this.axiosInstance.get('/strategies');
            return response.data;
        } catch (error) {
            vscode.window.showErrorMessage(`获取策略列表出错: ${error instanceof Error ? error.message : String(error)}`);
            return null;
        }
    }

    // 获取相册列表
    public async getAlbums(page: number = 1, order: string = 'newest', keyword: string = ''): Promise<ApiResponse<AlbumListResponseData> | null> {
        try {
            // 确保有token
            const token = await this.getToken();
            if (!token) {
                return null;
            }

            // 发送请求
            const response: AxiosResponse<ApiResponse<AlbumListResponseData>> = await this.axiosInstance.get(
                '/albums',
                { params: { page, order, keyword } }
            );
            return response.data;
        } catch (error) {
            vscode.window.showErrorMessage(`获取相册列表出错: ${error instanceof Error ? error.message : String(error)}`);
            return null;
        }
    }

    // 获取图片列表
    public async getImages(page: number = 1): Promise<ApiResponse<ImageListResponseData> | null> {
        try {
            // 确保有token
            const token = await this.getToken();
            if (!token) {
                return null;
            }

            // 发送请求
            const response: AxiosResponse<ApiResponse<ImageListResponseData>> = await this.axiosInstance.get(
                '/images',
                { params: { page } }
            );
            return response.data;
        } catch (error) {
            vscode.window.showErrorMessage(`获取图片列表出错: ${error instanceof Error ? error.message : String(error)}`);
            return null;
        }
    }

    // 删除图片
    public async deleteImage(key: string): Promise<ApiResponse<{}> | null> {
        try {
            // 确保有token
            const token = await this.getToken();
            if (!token) {
                return null;
            }

            // 发送请求
            const response: AxiosResponse<ApiResponse<{}>> = await this.axiosInstance.delete(`/images/${key}`);
            return response.data;
        } catch (error) {
            vscode.window.showErrorMessage(`删除图片出错: ${error instanceof Error ? error.message : String(error)}`);
            return null;
        }
    }
}